import { PageHeaderWrapper } from '@ant-design/pro-layout';

import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, message, Modal, Select, Spin } from 'antd';
import debounce from 'lodash/debounce';
import React, { useMemo, useRef, useState } from 'react';

import {
  addCustomerUsers,
  deleteCustomerUser,
  getCustomerUserByPage,
  userList,
} from '@/services/system/customer';
import type { SelectProps } from 'antd/es/select';
import { useLocation } from 'umi';
const { Option } = Select;
export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
}

function DebounceSelect<
  ValueType extends { key?: string; label: React.ReactNode; value: string | number } = any,
>({ fetchOptions, debounceTimeout = 800, ...props }: DebounceSelectProps<ValueType>) {
  const [fetching, setFetching] = useState(false);
  const [options, setOptions] = useState<ValueType[]>([]);
  const fetchRef = useRef(0);

  const debounceFetcher = useMemo(() => {
    const loadOptions = (value: string) => {
      fetchRef.current += 1;
      const fetchId = fetchRef.current;
      setOptions([]);
      setFetching(true);

      fetchOptions(value).then((newOptions) => {
        if (fetchId !== fetchRef.current) {
          // for fetch callback order
          return;
        }

        setOptions(newOptions);
        setFetching(false);
      });
    };

    return debounce(loadOptions, debounceTimeout);
  }, [fetchOptions, debounceTimeout]);

  return (
    <Select
      labelInValue
      filterOption={false}
      onSearch={debounceFetcher}
      notFoundContent={fetching ? <Spin size="small" /> : null}
      {...props}
      options={options}
    />
  );
}

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

async function fetchUserList(username: string): Promise<UserValue[]> {
  console.log('fetching user', username);
  return userList({ blurry: username }).then((res) => {
    return res.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  });
  // return fetch('https://randomuser.me/api/?results=5')
  //   .then((response) => response.json())
  //   .then((body) =>
  //     body.results.map(
  //       (user: { name: { first: string; last: string }; login: { username: string } }) => ({
  //         label: `${user.name.first} ${user.name.last}`,
  //         value: user.login.username,
  //       }),
  //     ),
  //   );
}

const CustomerUser: React.FC<{}> = (props) => {
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框

  const [formTitle, setFormTitle] = useState('新建客户'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable

  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable

  /**
   * 穿梭框的数据设置
   */
  const [value, setValue] = useState<UserValue[]>([]);
  const location = useLocation();
  console.log(location.query.id, '---ceshi1---');
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '用户名称', //表头显示的名称
      dataIndex: 'name', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
    },

    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },

    {
      title: '创建时间', //表头显示的名称
      search: false,
      dataIndex: 'createDate',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            // console.log(record, '----测试----');
            // 编辑用户
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑用户');
            form.setFieldsValue({
              name: record.name,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            // actionRef.current.reload();
            // setDeleteVisit(true);
            Modal.confirm({
              title: '是否要删除该客户下的用户',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await deleteCustomerUser({ id: record.id });
                actionRef.current.reload();
              },
            });
            // actionRef.current.reload();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const handleSubmit = async () => {
    console.log(form.getFieldsValue(), '---form.getFieldsValue()---');
    setConfirmLoading(true);
    await addCustomerUsers({
      customerId: location.query.id,
      userIds: form.getFieldsValue().userIds.map((item) => item.value),
    });
    // if (formTitle == '新建客户') {
    //   await addCustomer(form.getFieldsValue());
    // } else {
    //   await updateCustomer(form.getFieldsValue());
    // }
    setConfirmLoading(false);
    message.success('添加成功');
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };
  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable //表格Pro组件
        headerTitle="客户查询" //表头
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        revalidateOnFocus={false}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              // console.log(selectedRows, '---选取多行----');
              // 1.清空form
              setCreateOrUpdate(false);
              setFormTitle('新建客户');
              form.resetFields();
              //
              setModalVisit(true);
            }}
            type="primary"
          >
            增加用户
          </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          console.log(params, sort, filter);
          const result = await getCustomerUserByPage({ ...params, customerId: location.query.id });

          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
          // return  await new Promise({data:[{loginName:}], total:10, success: 0})
          // return {data:[], total:10, success: 0}
        }} //请求数据的地方，例子是用mock模拟数据，我是在后台请求的数据
        columns={columns} //上面定义的
        rowSelection={{}}
      />

      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        onCancel={() => setModalVisit(false)}
        confirmLoading={confirmLoading}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="用户" name="userIds">
            <DebounceSelect
              mode="multiple"
              value={value}
              placeholder="Select users"
              fetchOptions={fetchUserList}
              onChange={(newValue) => {
                setValue(newValue as UserValue[]);
              }}
              style={{ width: '100%' }}
            />
          </Form.Item>

          {/* <Form.Item
            label="名称"
            name="name"
            hidden={createOrUpdate}
            rules={[{ required: true, message: 'Please input your password!' }]}
          >
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};

export default CustomerUser;
